$(function () {
    var typeMap = getDict();
    console.log(typeMap);
    $("#jqGrid").jqGrid({
        url: baseURL + 'business/richtextcontent/list',
        datatype: "json",
        colModel: [
            {label: 'id', name: 'id', index: 'id', width: 50, key: true},
            {label: '标题', name: 'title', index: 'title', width: 80},
            {label: '项目', name: 'projectName', index: 'project_name', width: 80},
            // { label: '文本内容', name: 'content', index: 'content', width: 80 },
            {
                label: '分类',
                name: 'categoryCode',
                index: 'category_code',
                width: 80,
                formatter: function (value, options, row) {
                    if (typeMap.hasOwnProperty(value)) {
                        return typeMap[value]
                    }
                    return value;
                }
            },
            {label: '创建时间', name: 'createTime', index: 'create_time', width: 80},
            {label: '创建人', name: 'creator', index: 'creator', width: 80},
            {label: '修改时间', name: 'updateTime', index: 'update_time', width: 80},
            {label: '修改人', name: 'updator', index: 'updator', width: 80},
            {
                label: '是否可用', name: 'enabled', index: 'enabled', width: 80, formatter: function (value, options, row) {
                    return value === 1 ?
                        '<span class="label label-success">可用</span>' :
                        '<span class="label label-danger">已删除</span>';
                }
            }
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });

    $('#summernote').summernote({
        lang: 'zh-CN',
        height: 250,
        tabsize: 2,
        htmlMode: true,
        callbacks: {
            onImageUpload: function (files) {
                //上传图片到服务器
                var formData = new FormData();
                formData.append('file', files[0]);

                $.ajax({
                    url: baseURL + '/upload/image',//后台文件上传接口
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (r) {
                        console.log(JSON.stringify(r));
                        if (r.code == 0)
                            $('#summernote').summernote('insertImage', r.data);
                        else
                            alert("上传失败");
                    }, error: function () {
                        alert("上传失败");
                    }
                });
            }
        }
    });
    new AjaxUpload('#upload', {
        action: baseURL + 'upload/image',
        name: 'file',
        autoSubmit: true,
        responseType: "json",
        onSubmit: function (file, extension) {

            if (!(extension && /^(jpg|jpeg|png|gif)$/.test(extension.toLowerCase()))) {
                alert('只支持jpg、png、gif格式的图片！');
                return false;
            }
        },
        onComplete: function (file, r) {
            if (r.code == 0) {
                //alert(r.url);
                $("#imageUrlDiv").html('<img id="imageUrl" style="width:300px;margin-bottom:10px" src="'+r.data+'"><i class="imageDel" onclick="deleteImage();">×</i>');
            } else {
                alert(r.msg);
            }
        }
    });

    //初始化联动下拉框
    $("#categoryCodeParent").selectpicker({width:200, liveSearch: true, liveSearchPlaceholder: "搜索" });
    $("#categoryCode").selectpicker({width:200, liveSearch: true, liveSearchPlaceholder: "搜索",noneSelectedText: '--请选择--' });
    // 动态加载一级菜单
    initSelectOptions("categoryCodeParent", "ROOT");
});

function initSelectOptions(selectId, parentId) {
    var selectObj = $("#" + selectId);
    var data = {type: parentId}
    $.ajax({
        url : baseURL + "sys/dict/listByType",
        async : false,
        type : "POST",
        contentType: "application/json",
        data: JSON.stringify(data),
        success : function(result) {
            if (result.code==0) {
                var configs = result.list;
                selectObj.find("option:not(:first)").remove();
                for (var i in configs) {
                    var addressConfig = configs[i];
                    var optionValue = addressConfig.code;
                    var optionText = addressConfig.value;
                    selectObj.append(new Option(optionText, optionValue));
                }

                // 刷新select
                selectObj.selectpicker('refresh');
            } else {
                console.log('获取['+ parentId + ']信息失败，原因：' + result.errorMessage);
            }
        },
        error : function(result) {
            console.log('获取['+ parentId + ']信息失败，原因：' + result.errorMessage);
        }
    });// ajax
}

function initChildren() {
    // 当一级菜单变动时，初始化二级菜单
    var value = $("#categoryCodeParent").val();
    initSelectOptions("categoryCode", value);
}

function getDict() {
    var typeMap = {};
    var data = {del_flag: 0}
    $.ajax({
        type: "POST",
        url: baseURL + "sys/dict/listByType",
        contentType: "application/json",
        data: JSON.stringify(data),
        success: function (r) {
            if (r.code == 0) {
                var list = r.list;
                for (var i = 0; i < list.length; i++) {
                    var key = list[i].code;
                    typeMap[key] = list[i].value;
                }
            }
        }
    });
    return typeMap;
};

function deleteImage() {
    $(".imageBg").html("");
}

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        richtextContent: {},
        typeList: []
    },
    created() {
        this.getDict();
    },
    methods: {
        getDict: function () {
            var data = {type: 'newstype'}
            $.ajax({
                type: "POST",
                url: baseURL + "sys/dict/listByType",
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function (r) {
                    console.log(r);
                    if (r.code == 0) {
                        vm.typeList = r.list;
                    }
                }
            });
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.richtextContent = {};
            $("#imageUrlDiv").html("");
            $('#summernote').summernote('code', '');
            $('#categoryCode').selectpicker('val', vm.typeList[i].type);

        },
        update: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfoTongBu(id, function () {
                if (vm.richtextContent.imageUrl != '' && vm.richtextContent.imageUrl != undefined) {
                    $("#imageUrlDiv").html('<img id="imageUrl" style="width:300px;margin-bottom:10px" src="'+vm.richtextContent.imageUrl+'"><i class="imageDel" onclick="deleteImage();">×</i>');
                }
                for(var i=0;i<vm.typeList.length;i++){
                    if(vm.typeList[i].code==vm.richtextContent.categoryCode){
                        $('#categoryCodeParent').selectpicker('val', vm.typeList[i].type);
                        break;
                    }
                }
                $('#categoryCode').selectpicker('val', vm.richtextContent.categoryCode);
                $('#summernote').summernote('code', vm.richtextContent.content);
            });

        },
        saveOrUpdate: function (event) {
            $('#btnSaveOrUpdate').button('loading').delay(1000).queue(function () {
                var url = vm.richtextContent.id == null ? "business/richtextcontent/save" : "business/richtextcontent/update";
                vm.richtextContent.content = $('#summernote').summernote('code');
                vm.richtextContent.imageUrl = $('#imageUrl').attr("src");
                if($('#categoryCode').val()==''){
                    vm.richtextContent.categoryCode=$('#categoryCodeParent').val();
                }
                console.log(JSON.stringify(vm.richtextContent));
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json;charset=UTF-8",
                    data: JSON.stringify(vm.richtextContent),
                    datatype: "json",
                    success: function (r) {
                        if (r.code === 0) {
                            layer.msg("操作成功", {icon: 1});
                            vm.reload();
                            $('#btnSaveOrUpdate').button('reset');
                            $('#btnSaveOrUpdate').dequeue();
                        } else {
                            layer.alert(r.msg);
                            $('#btnSaveOrUpdate').button('reset');
                            $('#btnSaveOrUpdate').dequeue();
                        }
                    }
                });
            });
        },
        del: function (event) {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }
            var lock = false;
            layer.confirm('确定要删除选中的记录？', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                if (!lock) {
                    lock = true;
                    $.ajax({
                        type: "POST",
                        url: baseURL + "business/richtextcontent/delete",
                        contentType: "application/json",
                        data: JSON.stringify(ids),
                        success: function (r) {
                            if (r.code == 0) {
                                layer.msg("操作成功", {icon: 1});
                                $("#jqGrid").trigger("reloadGrid");
                            } else {
                                layer.alert(r.msg);
                            }
                        }
                    });
                }
            }, function () {
            });
        },
        getInfo: function (id) {
            $.get(baseURL + "business/richtextcontent/info/" + id, function (r) {
                vm.richtextContent = r.richtextContent;
            });
        },
        getInfoTongBu: function (id, callback) {
            $.get(baseURL + "business/richtextcontent/info/" + id, function (r) {
                vm.richtextContent = r.richtextContent;
                callback();
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                page: page
            }).trigger("reloadGrid");
        }
    }
});